package com.engine;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.Enumeration;
import java.util.TooManyListenersException;

import javax.comm.CommPortIdentifier;
import javax.comm.PortInUseException;
import javax.comm.SerialPort;
import javax.comm.SerialPortEvent;
import javax.comm.SerialPortEventListener;
import javax.comm.UnsupportedCommOperationException;

import org.apache.log4j.Category;

import com.command.EPSON;

public class SQEngine implements Runnable,SerialPortEventListener{
	static CommPortIdentifier portId;
    static Enumeration portList;

    InputStream inputStream;
    SerialPort serialPort;
    Thread readThread;
    static OutputStream outStream;
    static final Category log = Category.getInstance(SQEngine.class);
    private StringBuffer recv;
	public SQEngine()
	{
		boolean portavail=false;
		log.info("SQEngine initialize");
		recv=new StringBuffer();
		portList = CommPortIdentifier.getPortIdentifiers();
        while (portList.hasMoreElements()) {
            portId = (CommPortIdentifier) portList.nextElement();
            if (portId.getPortType() == CommPortIdentifier.PORT_SERIAL) {
            	log.info("COM: " + portId.getName());
                 if (portId.getName().equals(COMMPORT.commport)) {
			//                if (portId.getName().equals("/dev/term/a")) {
                	 if(!portavail)
                		 portavail=true;
                	 if(!portavail)
                		 init();
                }
            }
        }
        
        if(!portavail)
        	log.info("!Port is not availabe. Please check your commport");
	}
	
	private void init()
	{
		try {
			log.info("init SQApp...");
            serialPort = (SerialPort) portId.open("SQApp", 2000);
        } catch (PortInUseException e) 
        {
        	log.info(e.getLocalizedMessage());
        }
        try {
            inputStream = serialPort.getInputStream();
        } catch (IOException e) {
        	log.info(e.getLocalizedMessage());
        }
        try {
            serialPort.addEventListener(this);
        } catch (TooManyListenersException e) 
        {
        	log.info(e.getLocalizedMessage());
        }
        
        serialPort.notifyOnDataAvailable(true);
        try {
            serialPort.setSerialPortParams(COMMPORT.baudrate,
                COMMPORT.databits,
                COMMPORT.stopbits,
                COMMPORT.parity);
            outStream = serialPort.getOutputStream();
            
        } catch (UnsupportedCommOperationException e) 
        {
        	log.info(e.getLocalizedMessage());
        } catch (IOException e) {
			// TODO Auto-generated catch block
        	log.info(e.getLocalizedMessage());
		}
        new Thread(this).start();
	}
	
	public void run() {
		// TODO Auto-generated method stub
		try {
            Thread.sleep(20000);
        } catch (InterruptedException e) {System.out.println(e);}

	}

	public void serialEvent(SerialPortEvent event) {
		// TODO Auto-generated method stub
		switch(event.getEventType()) {
        case SerialPortEvent.BI:
        case SerialPortEvent.OE:
        case SerialPortEvent.FE:
        case SerialPortEvent.PE:
        case SerialPortEvent.CD:
        case SerialPortEvent.CTS:
        case SerialPortEvent.DSR:
        case SerialPortEvent.RI:
        case SerialPortEvent.OUTPUT_BUFFER_EMPTY:
            break;
        case SerialPortEvent.DATA_AVAILABLE:
            byte[] readBuffer = new byte[20];
            try {
            	int numBytes=0;
                while (inputStream.available() > 0) {
                    numBytes = inputStream.read(readBuffer);
                }
                if(numBytes>0)
                {
                	String tmprecv=new String(readBuffer).substring(0,numBytes);
                	if(tmprecv.equals("\n"))
                	{
                		//String resp=recv.toString();
                		recv=null;
                	}
                	else
                	{
                		if(recv==null)
                			recv=new StringBuffer();
                		recv.append(tmprecv);
                	}
                }
            } catch (IOException e) {log.info(e.getLocalizedMessage());}
            break;
        }
	}
	
	public void send(String model,String layanan,String noantrian)
	{
		if(outStream==null) return;
		try {
			String msgRtn ="";
			if (model.equals("epson"))
				msgRtn = new EPSON().print(layanan, noantrian);
			
			if(!msgRtn.equals(""))
				outStream.write(msgRtn.getBytes());
			
			//System.out.println("send: " + msgRtn);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			log.info("!send: " + e.getLocalizedMessage());
		}
	}
}
